// Copyright 2023 Leo <lipf160627@163.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package healthy

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func routerInit(g *gin.Engine) {
	installMiddleware(g)
	installController(g)
}

func installMiddleware(g *gin.Engine) {
}

func installController(g *gin.Engine) {
	// user RESTful resource
	healthy := g.Group("/healthy")
	{
		healthy.GET("/readiness", func(c *gin.Context) {
			if healthyIsReady() {
				c.JSON(http.StatusOK, gin.H{})
			}
		})

		healthy.GET("/liveness", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{})
		})
	}
}

func NewAndRun(debug bool) error {
	//  router := gin.Default()

	// 不用 gin.Logger()，不需要记录log
	router := gin.New()
	router.Use(gin.Recovery())

	if debug {
		router.Use(gin.Logger())
	}

	routerInit(router)

	server := &http.Server{
		Addr:         ":9000",
		Handler:      router,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
	}

	server.ListenAndServe()

	return nil
}
